package com.wstuo.itsm.request.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.config.category.entity.EventCategory;
import com.wstuo.itsm.domain.util.ModuleUtils;
import com.wstuo.itsm.request.dao.IEventCountDAO;
import com.wstuo.itsm.request.dto.EventCountDTO;
import com.wstuo.itsm.request.entity.EventCount;
import com.wstuo.common.util.StringUtils;
import com.wstuo.common.util.TimeUtils;

public class EventCountService implements IEventCountService {
	@Autowired
	private IEventCountDAO eventCountDAO;
	//获取当天编号数量
    public static int currentCount=0;
    //项目启动日期
    private String date=TimeUtils.format(new Date(),"yyyyMMdd");

    /**
     * 取得最新的编号
     */
    public int getLatesEventCodeNo() {
    	synchronized(EventCountService.class){
    		return EventCountService.currentCount;
    	}
	}

    /**
     * 设置值
     */
	public void setLatesEventCodeNo(int currentCount) {
		synchronized(EventCountService.class){
			EventCountService.currentCount = currentCount;
		}
	}
	/**
	 * 生成事件编码
	 * @param module
	 * @param eventCategroy
	 * @return 返回事件编码
	 */
	public synchronized String generateEventCode(String module, EventCategory eventCategory) {
		// 获取分类并得到自定义的请求规则
		String codeRule = "HD-";// 默认的请求规则为空
		if(ModuleUtils.ITSM_REQUEST.equals(module)){
			codeRule = "HD-";
		}else if(ModuleUtils.ITSM_CHANGE.equals(module)){
			codeRule = "Change-";
		}else if(ModuleUtils.ITSM_PROBLEM.equals(module)){
			codeRule = "PB-";
		}else if(ModuleUtils.ITSM_RELEASE.equals(module)){
			codeRule = "Rel-";
		}
		
		if (eventCategory != null 
				&& StringUtils.hasText(eventCategory.getCategoryCodeRule())){// 如果请求分类不为空，则使用分类定义的规则编码
			codeRule = eventCategory.getCategoryCodeRule()+ "-";// 赋值于分类规则
		}
		if(getLatesEventCodeNo()==0 || !date.equals(TimeUtils.format(new Date(),"yyyyMMdd"))){
			EventCountDTO dto = new EventCountDTO();
			dto.setType(module);
			setLatesEventCodeNo(eventCountDAO.eventCount(dto) + 1);
		}else{
			setLatesEventCodeNo(getLatesEventCodeNo() + 1);
		}
		String eventCode= new StringBuffer().append(codeRule)
				.append(TimeUtils.format(new Date(),"yyyyMMdd"))
				.append(String.format("%05d", getLatesEventCodeNo())).toString();
		return eventCode;
	}
	
	/**
	 * 保存事件统计记录
	 * @param entity
	 */
	@Transactional
	public void save(EventCount entity) {
		// TODO Auto-generated method stub
		eventCountDAO.save(entity);
	}
	
}
